package com.dtagri.fjwlw.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.LayoutParams;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.R;
import com.dtagri.fjwlw.api.FJwlwApi;
import com.dtagri.fjwlw.base.TGson;
import com.dtagri.fjwlw.bean.ADInfo;
import com.dtagri.fjwlw.bean.ADUrl;
import com.dtagri.fjwlw.bean.ServerBean;
import com.dtagri.fjwlw.bean.TjAreaMsg;
import com.dtagri.fjwlw.bean.TjCompanyRegion;
import com.dtagri.fjwlw.bean.UpdataInfo;
import com.dtagri.fjwlw.broadcastreceiver.TReceiver;
import com.dtagri.fjwlw.ui.api.ad.CycleViewPager;
import com.dtagri.fjwlw.ui.api.ad.CycleViewPager.ImageCycleViewListener;
import com.dtagri.fjwlw.util.DoubleClickExitHelper;
import com.dtagri.fjwlw.util.FJwlwConstant;
import com.dtagri.fjwlw.util.TToast;
import com.dtagri.fjwlw.util.UpdateUtil;
import com.dtagri.fjwlw.util.ViewFactory;
import com.dtagri.fjwlw.widget.CommonDialog;
import com.dtagri.fjwlw.widget.DialogHelper;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.update.UmengUpdateAgent;

/**
 * 主页面
 * 
 * @author wxjn
 * 创建日期:2015-09-01
 * 最近修改人:CL.
 * 修改日期: 2015-12-04
 */
public class MainActivity extends ActionBarActivity {
	//广告栏
	private List<ImageView> views = new ArrayList<ImageView>();
	private List<ADInfo> infos = new ArrayList<ADInfo>();
	private CycleViewPager cycleViewPager;	
	//	private String[] imageUrls;
	private List<ADUrl>adlist=new ArrayList<ADUrl>();
	private List<UpdataInfo> verlist=new ArrayList<UpdataInfo>();
	private String[] imageUrls = {"http://www.fjwlw.org/Tjwlw/images/bg1.png",
			"http://www.fjwlw.org/Tjwlw/images/bg2.png"};
	private String []imgurl;
	public static ReloadHandler handler;
	private Integer versioncode;
	private String updataLog;
	public TextView getTvBase() {
		return tvBase;
	}

	private TextView tvBase;// 不是基地,是公司名,有空改下
	private DoubleClickExitHelper mDoubleClickExit;
	public FragmentTabHost mTabHost;
	protected int baseIndex = 0;
	protected int tabIndex = 0;		//底部菜单下标

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getdata(AppContext.user.getServerIp());//获取广告栏图片地址
		configImageLoader();		//广告栏
		//广告栏
		initTabs();
		checkUpdate();		//检查更新
		initActionBar();
		mDoubleClickExit = new DoubleClickExitHelper(this);
		handler=new ReloadHandler();

	}

	//初始化底部菜单
	private void initTabs() {
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.container);
		if (android.os.Build.VERSION.SDK_INT > 10) {
			mTabHost.getTabWidget().setShowDividers(0);
		}
		mTabHost.setCurrentTab(0);

		ZMainTab[] values = ZMainTab.values();
		int i=0;
		for (ZMainTab mainTab : values) {
			TabSpec tab = mTabHost.newTabSpec(mainTab.getResName());
			View indicator = LayoutInflater.from(getApplicationContext())
					.inflate(R.layout.tab_indicator, null);
			TextView title = (TextView) indicator.findViewById(R.id.tab_title);
			Drawable drawable = this.getResources().getDrawable(
					mainTab.getResIcon());
			title.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null,
					null);
			title.setText(mainTab.getResName());
			tab.setIndicator(indicator);
			tab.setContent(new TabContentFactory() {
				@Override
				public View createTabContent(String tag) {
					System.out.println("tab--createTabContent");	
					return new View(MainActivity.this);
				}
			});
			//将Tab按钮添加进Tab选项卡中
			mTabHost.addTab(tab, mainTab.getClz(), null);

			/*mTabHost.getTabWidget().getChildTabViewAt(i).setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
						System.out.println("mTabHost--in--setOnClickListener:"+arg0.findFocus());
						System.out.println("mTabHost--in--setOnClickListener:"+arg0);	
						cycleViewPager.setAdVisibility(false);
						mTabHost.setCurrentTab(1);
				}
			});

			mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener(){
				@Override
				public void onTabChanged(String arg0) {
					System.out.println("mTabHost--in--setOnTabChangedListener:"+arg0);	

				}});*/

			i++;		
		}
		mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabStr) {
				if(tabStr.equals("我的")){
					if(cycleViewPager!=null){
						cycleViewPager.setAdVisibility(false);
					}


				}else if(tabStr.equals("主页")){
					if(cycleViewPager!=null){
						cycleViewPager.setAdVisibility(true);
					}

				}

			}});
	}
	//右上角菜单
	private void initActionBar() {
		ActionBar mActionBar = getSupportActionBar();
		View view = getLayoutInflater().inflate(
				R.layout.actionbar_custom_title, null);
		tvBase = (TextView) view.findViewById(R.id.tv_actionbar_base);
		mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mActionBar.setCustomView(view, params);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		showBaseSwitchDialog();
		return true;
	}

	private void checkUpdate() {
		UmengUpdateAgent.update(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppContext.isLogin()) {
			tvBase.setText(AppContext.user.getCompanyName());
		}
	}

	private void showBaseSwitchDialog() {
		if (!AppContext.isLogin()) {
			TToast.showToastShort("需要登录才能使用");
			return;
		}
		final CommonDialog pinterestDialogCancelable = DialogHelper
				.getPinterestDialogCancelable(this);
		pinterestDialogCancelable.setTitle("选择基地");
		pinterestDialogCancelable.setItems(convertRegionNames(),
				AppContext.userOperate.getCurBaseIndex(),
				new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				baseIndex = arg2;
				pinterestDialogCancelable.dismiss();

				TjCompanyRegion tjCompanyRegion = AppContext.user
						.getTjCompanyRegions().get(arg2);
				FJwlwApi.companyEquipment(
						tjCompanyRegion.getRegionId(), mHandler2);
			}
		});
		pinterestDialogCancelable.show();
	}

	private final AsyncHttpResponseHandler mHandler2 = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			TToast.showToastShort("切换基地失败!");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 保存用户选择
			AppContext.userOperate.setCurBaseIndex(baseIndex);
			AppContext.saveUserOperateInfo(AppContext.userOperate);

			List<TjCompanyRegion> tjCompanyRegions = AppContext.user
					.getTjCompanyRegions();
			TjCompanyRegion tjCompanyRegion = tjCompanyRegions
					.get(AppContext.userOperate.getCurBaseIndex());
			TToast.showToastShort("当前基地「" + tjCompanyRegion.getRegionName()+ "」");

			Type type = new TypeToken<List<TjAreaMsg>>() {
			}.getType();
			List<TjAreaMsg> tjAreaMsgs = TGson.gson.fromJson(new String(arg2),
					type);
			AppContext.saveAreaMsgInfo(tjAreaMsgs);
			TReceiver.sendBroadCast(MainActivity.this, TReceiver.CHANG_BASE);
		}

	};
	/**
	 * 获取广告图片信息的handler
	 */
	public  final AsyncHttpResponseHandler adhandler=new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			Type type = new TypeToken<List<ADUrl>>() {
			}.getType();

			try {
				adlist=TGson.gson.fromJson(new String(arg2), type);
				System.out.println("----adlist---"+adlist.size());
				imgurl=new String[adlist.size()];
				for(int i=0;i<adlist.size();i++){
					imgurl[i]=adlist.get(i).getPicUrl();
					System.out.println(adlist.get(i).getPicUrl()+"<--------图片地址");
					System.out.println(imgurl[i]+"***********");
				}

			} catch (JsonSyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				imgurl=imageUrls;
			}
			initialize(imgurl);
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			// TODO Auto-generated method stub
			TToast.showToast("获取数据失败");
			//获取数据失败时做出的处理，加载一张本地的图片
			imgurl=new  String[]{"1"};
			initialize(imgurl);
			cycleViewPager.setCycle(false);
			//屏蔽广告栏点击事件，避免后期添加点击跳转时出错
			cycleViewPager.setData(views, infos, null);
		}
	};
	/**
	 * 获取app版本号的handler
	 */
	public  final AsyncHttpResponseHandler versionhandler=new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			Type type = new TypeToken<List<UpdataInfo>>() {
			}.getType();

			try {
				verlist=TGson.gson.fromJson(new String(arg2), type);
//				imgurl=new String[adlist.size()];
				for(int i=0;i<verlist.size();i++){
//					imgurl[i]=verlist.get(i).getPicUrl();
					System.out.println(verlist.get(i).getVersionNum()+"<--------版本信息");
					System.out.println(verlist.get(i).getUpdateContent()+"*****更新内容******");
					versioncode=verlist.get(0).getVersionNum();
					updataLog=verlist.get(i).getUpdateContent();
				}
				if(versioncode<=getVersionCode()){
					System.out.println("-----不需要更新-------");
				}else{
					System.out.println("-------提示用户更新-------");
					new UpdateUtil(MainActivity.this, "index");
					
				}
			} catch (JsonSyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			initialize(imgurl);
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			// TODO Auto-generated method stub
//			TToast.showToast("获取数据失败");
//			//获取数据失败时做出的处理，加载一张本地的图片
//			imgurl=new  String[]{"1"};
//			initialize(imgurl);
//			cycleViewPager.setCycle(false);
//			//屏蔽广告栏点击事件，避免后期添加点击跳转时出错
//			cycleViewPager.setData(views, infos, null);
		}
	};
	public Integer getVersionCode(){
		Integer ver=0;
		try {
			ver=this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ver;
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return mDoubleClickExit.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * list到string[]
	 * 
	 * @return
	 */
	private String[] convertRegionNames() {
		List<TjCompanyRegion> tjCompanyRegions = AppContext.user
				.getTjCompanyRegions();
		String[] ss = new String[tjCompanyRegions.size()];
		for (int i = 0; i < tjCompanyRegions.size(); i++) {
			TjCompanyRegion tjCompanyRegion = tjCompanyRegions.get(i);
			ss[i] = tjCompanyRegion.getRegionName();
		}
		return ss;
	}
	/**
	 * 广告栏
	 * 版本信息检测
	 */
	void getdata(String adIp){

		FJwlwApi.getadUrl(adhandler,adIp);
		FJwlwApi.getversionUrl(versionhandler);
	}
	@SuppressLint("NewApi")
	private void initialize(String []imgurl) {

		cycleViewPager = (CycleViewPager) getFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content);

		if(imgurl.length>0){
			for(int i = 0; i < imgurl.length; i ++){
				ADInfo info = new ADInfo();
				info.setUrl(imgurl[i]);
				info.setContent("图片-->" + i );
				infos.add(info);
		
			}
			System.out.println("imgurl------"+imgurl);
			System.out.println("url长度----------"+imgurl.length);
			System.out.println("info长度"+infos.size());
			// 将最后一个ImageView添加进来
			views.add(ViewFactory.getImageView(this, infos.get(infos.size() - 1).getUrl()));
			for (int i = 0; i < infos.size(); i++) {
				views.add(ViewFactory.getImageView(this, infos.get(i).getUrl()));
			}
			// 将第一个ImageView添加进来
			views.add(ViewFactory.getImageView(this, infos.get(0).getUrl()));

			// 设置循环，在调用setData方法前调用
			cycleViewPager.setCycle(true);

			// 在加载数据前设置是否循环
			cycleViewPager.setData(views, infos, mAdCycleViewListener);
			//设置轮播
			cycleViewPager.setWheel(true);

			// 设置轮播时间，默认5000ms
			cycleViewPager.setTime(3000);
			//设置圆点指示图标组居中显示，默认靠右
			cycleViewPager.setIndicatorCenter();
		}
	}
	//广告栏点击事件
	private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() {

		@Override
		public void onImageClick(ADInfo info, int position, View imageView) {
			if (cycleViewPager.isCycle()) {
				//				position = position - 1;
				////				该功能暂时屏蔽，点击监听事件已经完成
				//				Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
				//				intent.putExtra("url",adlist.get(position).getWebUrl());
				//				intent.putExtra("title", adlist.get(position).getTitle());
				//				startActivity(intent);
			}
		}

	};

	/**
	 * //广告栏
	 * 配置ImageLoder
	 */
	private void configImageLoader() {
		// 初始化ImageLoader
		@SuppressWarnings("deprecation")
		DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ad_stub) // 设置图片下载期间显示的图片
		.showImageForEmptyUri(R.drawable.ad_empty) // 设置图片Uri为空或是错误的时候显示的图片
		.showImageOnFail(R.drawable.ad_error) // 设置图片加载或解码过程中发生错误显示的图片
		.cacheInMemory(true) // 设置下载的图片是否缓存在内存中
		.cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
		// .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
		.build(); // 创建配置过得DisplayImageOption对象

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(options)
				.threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
		ImageLoader.getInstance().init(config);		
	}
	public void ReLoad(List<ImageView> views,List<ADInfo> infos,String adIp){
		views.clear();
		infos.clear();
		getdata(adIp);
	}
	public class ReloadHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.arg1==FJwlwConstant.Handler_flag_ad){
				ReLoad(views, infos,msg.obj.toString());
//				views.clear();
//				infos.clear();
				//				views.removeAll(infos);
//				imgurl=null;
//				imageUrls=null;
//				getdata();
				//				initialize(imgurl);

			}

		}
	}
}
